package com.health.ts.exception;

import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.health.ts.constant.ApiResult;
import com.health.ts.controller.BaseController;
import com.yomahub.tlog.context.TLogContext;

import lombok.extern.slf4j.Slf4j;

/**
 * 异常全局处理
 * @author Administrator
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
	
    /**
     * 处理系统异常
     * @param e
     * @param response
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ApiResult handleException(Exception e, HttpServletResponse response) {
    	log.error("发生系统异常： ", e);
    	String traceId = setTraceInfo(response);
    	return ApiResult.error("系统异常，错误id："+traceId+" 错误消息："+e.getMessage()+" 堆栈信息："+ExceptionUtils.getStackTrace(e));
    }
    
    /**
     * 处理业务异常
     * @param e
     * @param response
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ApiResult handleBusinessException(BusinessException e, HttpServletResponse response) {
    	log.warn("业务错误：{}", e.getMessage());
    	setTraceInfo(response);
    	return ApiResult.failed(e.getCode(), e.getMessage());
    }
    
    /**
     * 处理参数校验异常
     * @param e
     * @param response
     * @return
     */
    @ExceptionHandler(value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ApiResult handleValidatedException(Exception e, HttpServletResponse response) {
    	String message = null;
        if (e instanceof MethodArgumentNotValidException) {
            // BeanValidation exception
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            message = ex.getBindingResult().getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(", "));
        } else if (e instanceof ConstraintViolationException) {
            // BeanValidation GET simple param
            ConstraintViolationException ex = (ConstraintViolationException) e;
            message = ex.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(", "));
        } else if (e instanceof BindException) {
            // BeanValidation GET object param
            BindException ex = (BindException) e;
            message = ex.getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(", "));
        }
		log.warn("入参校验失败：{}", message);
    	setTraceInfo(response);
        return ApiResult.failed("入参校验失败："+message);
    }
    
    /**
     * 处理角色权限校验异常
     * @param e
     * @param request
     * @param response
     * @return
     */
    @ExceptionHandler(UnauthorizedException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ApiResult handleUnauthorizedException(UnauthorizedException e, HttpServletRequest request, HttpServletResponse response) {
    	String uri = request.getRequestURI();
    	log.warn("接口【{}】角色权限校验错误：{}", uri, e.getMessage());
    	setTraceInfo(response);
    	return ApiResult.failed(String.format("没有接口【%s】访问权限：%s", uri, e.getMessage()));
    }
    
    /**
     * 设置返回错误追踪信息
     * @param response
     */
    private String setTraceInfo(HttpServletResponse response) {
    	String traceId = TLogContext.getTraceId();
//      response.setHeader("traceId", traceId);
        response.setHeader("content-type", BaseController.JSON_UTF8);
        return traceId;
    }
}
